<?php
declare (strict_types = 1);

namespace app\common\middleware;

use think\Exception;
use think\Response;

class AccessCheck
{
    const SIGN_SIGNED = '@';
    const SIGN_UNSIGNED = '?';

    /**
     * @param $request
     * @param \Closure $next
     * @param string $sign
     * @return mixed|\think\response\Json
     * @throws Exception
     */
    public function handle($request, \Closure $next, string $sign)
    {

        if ($sign !== static::SIGN_SIGNED && $sign !== static::SIGN_UNSIGNED)
            throw new Exception(__CLASS__ . ' 配置错误.');

        //必须登录
        if ($sign === static::SIGN_SIGNED){
            if (app()->user->isGuest()){
                return app()->user->loginRequired();
            }
        }

        //游客身份可访问
        if ($sign === static::SIGN_UNSIGNED){
            //必须不能登录
            if (!app()->user->isGuest()) {
                return redirect((string)url(request()->rootPathInfo()));
            }
        }

        return $next($request);
    }
}
